<?php

namespace app\admin\model\scanwork;

use think\Model;

/**
 * 工艺路线模型
 */
class ProcessRoute extends Model
{
    // 表名
    protected $name = 'scanwork_process_route';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
        'route_type_text',
        'status_text'
    ];

    /**
     * 路线类型列表
     */
    public function getRouteTypeList()
    {
        return [
            1 => __('标准路线'),
            2 => __('备选路线'),
            3 => __('临时路线')
        ];
    }

    /**
     * 状态列表
     */
    public function getStatusList()
    {
        return [
            0 => __('草稿'),
            1 => __('审核中'),
            2 => __('已发布'),
            3 => __('已归档')
        ];
    }

    /**
     * 路线类型文本
     */
    public function getRouteTypeTextAttr($value, $data)
    {
        $value = $value ?? $data['route_type'] ?? '';
        $list = $this->getRouteTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 状态文本
     */
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?? $data['status'] ?? '';
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 关联产品
     */
    public function product()
    {
        return $this->belongsTo('Product', 'product_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联产品型号
     */
    public function model()
    {
        return $this->belongsTo('ProductModel', 'model_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联工艺步骤
     */
    public function steps()
    {
        return $this->hasMany('ProcessRouteStep', 'route_id', 'id');
    }

    /**
     * 关联创建人
     */
    public function creator()
    {
        return $this->belongsTo('app\admin\model\Admin', 'creator_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 生成路线编码
     */
    public static function generateRouteCode()
    {
        $prefix = 'RT-';
        $date = date('Ymd');
        $lastRoute = self::where('route_code', 'like', $prefix . $date . '%')
            ->order('id', 'desc')
            ->value('route_code');
        
        if ($lastRoute) {
            $lastNum = intval(substr($lastRoute, -4));
            $newNum = str_pad($lastNum + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $newNum = '0001';
        }
        
        return $prefix . $date . $newNum;
    }

    /**
     * 计算总标准工时
     */
    public function calculateTotalTime()
    {
        $steps = $this->steps()->select();
        $totalTime = 0;
        
        foreach ($steps as $step) {
            $totalTime += $step->standard_time + $step->setup_time;
        }
        
        return $totalTime;
    }

    /**
     * 获取工艺路线流程图数据
     */
    public function getFlowChart()
    {
        $steps = ProcessRouteStep::where('route_id', $this->id)
            ->order('sequence', 'asc')
            ->select();
        
        $dependencies = ProcessRouteDependency::where('route_id', $this->id)
            ->select();
        
        $nodes = [];
        $edges = [];
        
        foreach ($steps as $step) {
            $nodes[] = [
                'id' => $step->id,
                'label' => $step->process_name,
                'sequence' => $step->sequence,
                'standard_time' => $step->standard_time,
                'is_key_process' => $step->is_key_process
            ];
        }
        
        foreach ($dependencies as $dep) {
            $edges[] = [
                'from' => $dep->depend_step_id,
                'to' => $dep->step_id,
                'type' => $dep->dependency_type,
                'lag_time' => $dep->lag_time
            ];
        }
        
        return [
            'nodes' => $nodes,
            'edges' => $edges
        ];
    }

    /**
     * 复制工艺路线
     */
    public function copyRoute($newVersion = null)
    {
        $newRoute = $this->toArray();
        unset($newRoute['id']);
        $newRoute['route_code'] = self::generateRouteCode();
        $newRoute['version'] = $newVersion ?: ($this->version + 0.1);
        $newRoute['status'] = 0;
        $newRoute['is_default'] = 0;
        $newRoute['createtime'] = time();
        $newRoute['updatetime'] = time();
        
        $newRouteModel = self::create($newRoute);
        
        // 复制工艺步骤
        $steps = $this->steps()->select();
        $stepMapping = []; // 旧ID => 新ID
        
        foreach ($steps as $step) {
            $newStep = $step->toArray();
            $oldStepId = $newStep['id'];
            unset($newStep['id']);
            $newStep['route_id'] = $newRouteModel->id;
            $newStepModel = ProcessRouteStep::create($newStep);
            $stepMapping[$oldStepId] = $newStepModel->id;
        }
        
        // 复制依赖关系
        $dependencies = ProcessRouteDependency::where('route_id', $this->id)->select();
        foreach ($dependencies as $dep) {
            $newDep = $dep->toArray();
            unset($newDep['id']);
            $newDep['route_id'] = $newRouteModel->id;
            $newDep['step_id'] = $stepMapping[$newDep['step_id']] ?? 0;
            $newDep['depend_step_id'] = $stepMapping[$newDep['depend_step_id']] ?? 0;
            ProcessRouteDependency::create($newDep);
        }
        
        return $newRouteModel;
    }
}

